package com.example.demo.xml;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement
@XmlAccessorType
@XmlType(propOrder = {"id","age","name", "computers"})
@Data
public class Student {

    private Long id;

    private String name;

    private Integer age;

    private List<Computer> computers;

    public static void main(String[] args) throws JAXBException {
        Student student = new Student();
        student.setId(1L);
        student.setAge(24);
        student.setName("ben");

        Computer computer1 = new Computer();
        computer1.setComName("苹果");
        computer1.setPrice(241);

        Computer computer2 = new Computer();
        computer2.setComName("联想");
        computer2.setPrice(242);

        ArrayList<Computer> computers = new ArrayList<>();
        computers.add(computer1);
        computers.add(computer2);
        student.setComputers(computers);
        StringWriter stringWriter = new StringWriter();

        JAXBContext jaxbContext = JAXBContext.newInstance(student.getClass());
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(student, stringWriter);
        System.out.println(stringWriter.toString());


        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<student>\n" +
                "    <id>2</id>\n" +
                "    <age>3</age>\n" +
                "    <name>4</name>\n" +
                "</student>";

        jaxbContext = JAXBContext.newInstance(Student.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Object unmarshal = unmarshaller.unmarshal(new StringReader(xml));
        System.out.println(JSONObject.toJSONString(unmarshal));
    }
}
